package wechat.handler.util.transform;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;

public class XmlToMap {
	public static Map<String, String> buildMapByStringValue(String xmlStr, List<String> xpathList)
			throws DocumentException {
		Map<String, String> map = new TreeMap<String, String>();
		Document document = DocumentHelper.parseText(xmlStr);
		for (String xpath : xpathList) {
			Node node = document.selectSingleNode(xpath);
			if (node != null) {
				String key = node.getName();
				String value = node.getStringValue();
				map.put(key, value);
			}
		}

		return map;
	}

	public static Map<String, String> buildMapByText(String xmlStr, List<String> xpathList) throws DocumentException {
		Map<String, String> map = new TreeMap<String, String>();
		Document document = DocumentHelper.parseText(xmlStr);
		for (String xpath : xpathList) {
			Node node = document.selectSingleNode(xpath);
			if (node != null) {
				String key = node.getName();
				String value = node.getText();
				map.put(key, value);
			}
		}

		return map;
	}
}
